package com.cloudminds.resttest.helper;

import com.cloudminds.resttest.api.CallManager;
import com.cloudminds.resttest.ice.AiasIceClient;
import com.cloudminds.resttest.utils.Base64Utils;
import com.cloudminds.resttest.utils.FileUtils;
import com.cloudminds.resttest.vo.CallParams;
import org.json.JSONObject;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;

public class AsrHelper {

    private static AsrHelper asrHelper;
    private File[] audioPaths;
    private ArrayList<byte[]> audioList = new ArrayList<>();
    private int AUDIO_PER_SECTION_LEN = 5*1024*1024;
    private static int index = 0;
    private Thread sendThread;
    private boolean asrEnable = false;
    private long sendNumber = 0;
    private long responseNumber = 0;
    private CallManager callManager = null;
    private AiasIceClient aiasIceClient ;

     public AsrHelper(CallManager callManager, AiasIceClient aiasIceClient){
         this.callManager = callManager;
         this.aiasIceClient = aiasIceClient;
         sendThread = new Thread(new SendAsrRunnable());
         sendThread.start();
         asrHelper = this;
     }

//     public static AsrHelper getAsrHelper(){
//         if (asrHelper == null){
//             asrHelper = new AsrHelper();
//         }
//         return  asrHelper;
//     }

     private void loadAudios(String path){
         File file = new File(path+"/audios");
         System.out.println("Audio folder path:"+file.getAbsolutePath());
         //遍历audios文件夹下的音频文件
         if (file.exists()){
             audioPaths = file.listFiles(new FilenameFilter() {
                 @Override
                 public boolean accept(File dir, String name) {
                     String s = name.toLowerCase();
                     if (s.startsWith("._")){
                         return false;
                     }
                     return s.endsWith(".pcm") || s.endsWith(".avi");
                 }
             });
         }

         audioList.clear();
         //读取音频文件
         try {
             for (File item:audioPaths) {
                 byte[] audio = FileUtils.getContent(item);
                 if (audio!=null && audio.length>0){
                     audioList.add(audio);
                 }
             }
         }catch (Exception e){
             e.printStackTrace();
         }
     }

    private void loadAudios(File name){
        audioList.clear();
        //读取音频文件
        try {
                byte[] audio = FileUtils.getContent(name);
                if (audio!=null && audio.length>0){
                    audioList.add(audio);
                }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

     public void startAsr(){
         if (audioList.size()==0){
             String path = new File("").getAbsolutePath();
             loadAudios(path);
         }
         asrEnable = true;
     }

    public JSONObject startAsr1(String sid, String question){
        audioList.clear();
        asrEnable = true;
        JSONObject json = sendtestText(sid,question);
        return json;
    }

   /* public JSONObject startAsr(File fileName){
         loadAudios(fileName);
        asrEnable = true;
       // sendThread.start();
       JSONObject json =  sendAudioData(audioList.get(0));
        return json;
    }*/

     public void stopAsr(){
         asrEnable = false;
     }

     public void receivedAnswer(){
         responseNumber++;
     }


    /**
     * cloudasr 上传audio
     * @param audioBytes
     */
    public JSONObject sendAudioData(final byte[] audioBytes){
        JSONObject json = new JSONObject();
        try {
            if (null ==  audioBytes){
                System.out.println("audio is null ,return");
                return new JSONObject();
            }
            System.out.println("Send audio size:"+ audioBytes.length);

            String audioString  = Base64Utils.encodeToString(audioBytes);
            long resLen = audioString.length()%AUDIO_PER_SECTION_LEN;
            int blockNum = (int) (audioString.length()/AUDIO_PER_SECTION_LEN) + (audioString.length()%AUDIO_PER_SECTION_LEN>0?1:0);

            long seq = System.currentTimeMillis();
            for (int i=0;i<blockNum;i++){
                json.put("type","SpeechStream");
                json.put("seq", seq);
                json.put("sid", callManager.getSessionId());

                json.put("appType","pepper");
                json.put("tenantId",CallParams.TENANT_ID);
                json.put("serviceCode", CallParams.SERVICE_CODE);

                JSONObject dataJson = new JSONObject();
                dataJson.put("duration",1000);
                dataJson.put("rate",16000);
                dataJson.put("channel",1);
                dataJson.put("language","zh");
                dataJson.put("format","PCM");
                dataJson.put("account",CallParams.USER_NAME);
                int index = (int) (i*AUDIO_PER_SECTION_LEN);

                if (i == blockNum-1){
                    dataJson.put("flag",2);  //段尾
                    dataJson.put("speech",audioString.substring(index,audioString.length()));
                } else if(i==0) {
                    dataJson.put("flag",0); //段首
                    dataJson.put("speech",audioString.substring(index,AUDIO_PER_SECTION_LEN));
                } else {
                    dataJson.put("flag",1); //段中
                    dataJson.put("speech",audioString.substring(index,index+AUDIO_PER_SECTION_LEN));
                }
                json.put("data",dataJson);
                json.put("testText","你叫什么名字?");

                if (null != aiasIceClient){
                    String jsonString = json.toString();
                    //PushClient.getInstance().push2AiAs(jsonString);
                    aiasIceClient.sendAudio(jsonString);
                }

            }
            sendNumber++;

        }catch (Exception e){
            e.printStackTrace();
        }
        return json;
    }

    public JSONObject sendtestText(String sid, String question){
        JSONObject json = new JSONObject();
        byte[] audioBytes = new byte[0];
        try {
            if (null ==  audioBytes){
                System.out.println("audio is null ,return");
                return new JSONObject();
            }
            System.out.println("Send audio size:"+ audioBytes.length);

            String audioString  = Base64Utils.encodeToString(audioBytes);
            long resLen = audioString.length()%AUDIO_PER_SECTION_LEN;
            int blockNum = (int) (audioString.length()/AUDIO_PER_SECTION_LEN) + (audioString.length()%AUDIO_PER_SECTION_LEN>0?1:0);

            long seq = System.currentTimeMillis();
            for (int i=0;i<=blockNum;i++){
                json.put("type","SpeechStream");
                json.put("seq", seq);
               // json.put("sid", callManager.getSessionId());
                json.put("sid", sid);
                json.put("appType","pepper");
                json.put("tenantId",CallParams.TENANT_ID);
                json.put("serviceCode", CallParams.SERVICE_CODE);

                JSONObject dataJson = new JSONObject();
                dataJson.put("duration",1000);
                dataJson.put("rate",16000);
                dataJson.put("channel",1);
                dataJson.put("language","zh");
                dataJson.put("format","PCM");
                dataJson.put("account",CallParams.USER_NAME);
                int index = (int) (i*AUDIO_PER_SECTION_LEN);

                dataJson.put("flag",2);  //段尾
                dataJson.put("speech",audioString.substring(index,audioString.length()));
               /* if (i == blockNum-1){
                    dataJson.put("flag",2);  //段尾
                    dataJson.put("speech",audioString.substring(index,audioString.length()));
                } else if(i==0) {
                    dataJson.put("flag",0); //段首
                    dataJson.put("speech",audioString.substring(index,AUDIO_PER_SECTION_LEN));
                } else {
                    dataJson.put("flag",1); //段中
                    dataJson.put("speech",audioString.substring(index,index+AUDIO_PER_SECTION_LEN));
                }*/
                json.put("data",dataJson);
                json.put("testText",question);

                  aiasIceClient = new AiasIceClient();
                if (null != aiasIceClient){
                    String jsonString = json.toString();
                    //PushClient.getInstance().push2AiAs(jsonString);
                   int result =  aiasIceClient.sendAudio(jsonString);
                   System.out.print("发送状态："+result);
                }

            }
            sendNumber++;

        }catch (Exception e){
            e.printStackTrace();
        }
        return json;
    }

    private long lastLogTime = -1;

    class SendAsrRunnable implements Runnable{
        public void run(){
            while(true){
                if (asrEnable){

                    if (null!=audioList && audioList.size()>0){
                        index = index<audioList.size()?index:0;
                        sendAudioData(audioList.get(index));
                        index++;
                    }

                    if (lastLogTime>0){
                        long interval = System.currentTimeMillis()-lastLogTime;
                        if (interval>60*1000){
                            System.out.println("\n--------------  ASR Counter ------------");
                            System.out.println("Sent number:"+sendNumber + "  Received number:"+responseNumber);
                            System.out.println("--------------  End ASR Counter ------------\n");
                            lastLogTime = System.currentTimeMillis();
                        }
                    } else {
                        lastLogTime = System.currentTimeMillis();
                    }
                }

                try {
                    Thread.sleep(CallParams.ASR_SEND_INTERVAL*1000);
                }catch (Exception e){

                }
            }
        }
    }

}
